package portal.manager.impl;

import java.util.Hashtable;

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceFactory;
import org.osgi.util.tracker.ServiceTracker;

import portal.manager.service.PortalManagerService;
import portal.manager.tracker.BeanManagerTracker;
import portal.manager.tracker.HttpServiceTracker;
import portal.manager.tracker.JSONServiceTracker;
import portal.manager.tracker.PortalPanelTracker;

public class PortalManagerActivator implements BundleActivator {

	private ServiceTracker httpServiceTracker;
	private ServiceTracker beanManagerTracker;
	private ServiceTracker jsonServiceTracker;
	private ServiceTracker portalPanelTracker;
	
	/**
	 * 
	 */
	public void start(final BundleContext context) throws Exception {

/*		
		for( Object key : System.getProperties().keySet() ) {
			if( !((String)key).contains("osgi")) continue;
			System.out.printf(  "%s=%s\n",  
					key,
					System.getProperty((String)key)
					);
		}
*/
		
		ServiceFactory service = new PortalManagerServiceFactory();
		
		Hashtable<String,Object> attrs = new Hashtable<String,Object>(2);
		attrs.put("bind.protocol", "json-rpc");
		attrs.put("bind.name", "portal");
		// register the service
		context.registerService(PortalManagerService.class.getName(), service, attrs);

		// create a tracker and track the service
		httpServiceTracker = new HttpServiceTracker(context);
		httpServiceTracker.open();

		beanManagerTracker = new BeanManagerTracker( context );		
		beanManagerTracker.open();

		portalPanelTracker = PortalPanelTracker.createPortalPanelTracker(context);		
		portalPanelTracker.open();

		try {
			jsonServiceTracker = JSONServiceTracker.createJSONServiceTracker(context);
			jsonServiceTracker.open();
			
		}
		catch( Exception e ) {
			System.out.printf( "JSON Service Tracker registration error = %s\n", e.getMessage());
		}
	}
	
	public void stop(BundleContext context) throws Exception {

		// close the service tracker
		beanManagerTracker.close();
		beanManagerTracker = null;

		httpServiceTracker.close();
		httpServiceTracker = null;

		portalPanelTracker.close();		
		portalPanelTracker = null;

		if( null!=jsonServiceTracker ) {
			jsonServiceTracker.close();
			jsonServiceTracker = null;			
		}
		
	}

}
